import { Tag } from '../models'

/**
 * 创建标签
 * @param  {Int}  userId 用户信息
 * @param  {String} name   名称
 * @param  {Boolean} isFolder 是否为目录
 * @param  {Int} folderId 目录ID
 * @param  {Int} show     显示模式
 * @return {Tag} 标签实例
 */
export const create = async (userId, { name, folderId, show, isFolder }) => {
  let tag = await Tag.findOne({ where: { name } })
  if (tag !== null) {
    throw new Error(`${ERRORS.DBERR.ERR_DUPLICATE_RECORD}`)
  }
  tag = await Tag.create({
    userId,
    name,
    isFolder,
    folderId,
    show
  })
  return tag
}

/**
 * Update an existing tag
 * @param {int} tag
 * @param {int} userId
 * @param {object} data
 * @return {object} Tag
 */
export const pin = async (tagId, show) => {
  let tag = await Tag.findById(tagId)
  if (tag == null) {
    throw new Error(`${ERRORS.DBERR.ERR_RECORD_NOT_FOUND}`)
  }
  tag.show = show
  return await tag.save()
}

/**
 * Remove an existing tag
 * @param {int} tagId
 * @param {int} userId
 * @return {object} Tag
 */
export const remove = async (tagId, userId) => {
  let tag = await Tag.findById(tagId)
  if (tag == null) {
    throw new Error(`${ERRORS.DBERR.ERR_RECORD_NOT_FOUND}`)
  }
  if (userId && tag.userId != userId) {
    throw new Error(`${ERRORS.DBERR.ERR_UNAUTHORIZED_OPERATION}`)
  }
  return await tag.destroy()
}

/**
 * List all tags
 * Order by show then searchCount
 * @param {String} name
 * @param {int} folderId
 * @param {int} show
 * @return {array} Tags
 */
export const findAllTags = async ({ name, folderId, show }) => {
  let query = {}
  if (name) {
    query.name = { $like: `%${name}%` }
  }
  if (folderId != null) {
    query.folderId = folderId
  }
  if (show != null) {
    if (show >= 1) {
      query.show = { $gte: 1 }
    } else {
      query.show = show
    }
  }
  const result = await Tag.findAll({
    where: query,
    order: [['show', 'DESC'], ['searchCount', 'DESC']]
  })
  return result
}
